<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card class="box-card">
      <!-- 使用elemnet ui的格栅系统,搜索框 -->
      <el-row :gutter="18">
        <!-- 搜索框 -->
        <el-col :span="8">
          <el-input
            placeholder="请输入查询内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getuserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getuserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogFormVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="user">
            <el-switch
              v-model="user.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChange(user.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <!-- 使用插槽获取当前点击的用户信息  -->
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showAmendUser(scope.row.id)"
            ></el-button>
            <el-tooltip content="修改权限" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-bangzhu"
                size="mini"
                @click="allotUserRights(scope.row)"
              ></el-button>
            </el-tooltip>

            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUserInfo(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页页面功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 3, 5, 7, 9]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogFormVisible"
      center
      width="40%"
      destroy-on-close
    >
      <el-form :model="userFormAdd" :rules="userAddRules" ref="addUserInfoRef">
        <el-form-item
          label="用户名称："
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input v-model="userFormAdd.username"></el-input>
        </el-form-item>
        <el-form-item
          label="用户密码："
          :label-width="formLabelWidth"
          prop="password"
        >
          <el-input v-model="userFormAdd.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱：" :label-width="formLabelWidth" prop="email">
          <el-input v-model="userFormAdd.email" type="email"></el-input>
        </el-form-item>

        <el-form-item
          label="手机号："
          :label-width="formLabelWidth"
          prop="mobile"
        >
          <el-input
            placeholder="请输入手机号"
            v-model="userFormAdd.mobile"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserInfo">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog
      title="修改信息"
      :visible.sync="dialogShowAmendUser"
      width="40%"
      destroy-on-close
    >
      <!-- 修改用户信息表单 -->
      <el-form
        :model="userEditPut"
        :rules="userEditPutRules"
        ref="userEditPutRef"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input v-model="userEditPut.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userEditPut.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="userEditPut.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogShowAmendUser = false">取 消</el-button>
        <el-button type="primary" @click="userEditPutInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户权限对话框 -->
    <el-dialog
      title="修改权限"
      :visible.sync="dialogAllotRights"
      width="40%"
      @close="closeClear"
    >
      <div>
        <p><strong>当前的用户：</strong>{{ allotUserInfo.username }}</p>
        <p><strong>当前的角色：</strong>{{ allotUserInfo.role_name }}</p>
        <p>
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleRightsList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAllotRights = false">取 消</el-button>
        <el-button type="primary" @click="putUserSelect">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义手机校验规则
    const mobileRule = (rule, value, callback) => {
      const regMobile =
        /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/
      if (!value) return callback(new Error('手机号码不能为空！'))
      if (regMobile.test(value)) return callback()
      callback(new Error('请输入合法的手机号码！'))
    }
    return {
      // 查询用户的信息
      queryInfo: {
        query: '',
        // 当前页码 默认为1
        pagenum: Number(window.sessionStorage.getItem('newPagenum')) || 1,
        // 当前页面存储多少条数据 默认为1
        pagesize: Number(window.sessionStorage.getItem('newSize')) || 1
      },
      // 请求到的所有的用户信息
      userList: [],
      total: 0,
      // 添加用户的对话框信息
      dialogTableVisible: false,
      dialogFormVisible: false,
      // 添加的用户信息
      userFormAdd: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      formLabelWidth: '100px',
      // 添加用户信息验证规则
      userAddRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名在3~10位之间' }
        ],
        password: [
          { required: true, message: '密码不能为空' },
          { min: 6, max: 15, message: '用户名在6~15位之间' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [{ validator: mobileRule, trigger: ['blur', 'change'] }]
      },
      // 控制修改用户信息对话框的显示与隐藏
      dialogShowAmendUser: false,
      // 查询到的用户信息
      userEditPut: {},
      // 修改用户信息验证规则
      userEditPutRules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [{ validator: mobileRule, trigger: ['blur', 'change'] }]
      },
      // 控制分配角色的对话框显示与隐藏
      dialogAllotRights: false,
      // 需要分配角色的用户信息
      allotUserInfo: {},
      roleRightsList: [],
      selectedRoleId: ''
    }
  },
  // 钩子，在vue渲染到页面之前将数据渲染到页面当中
  created() {
    this.getuserList()
  },
  methods: {
    // 获取全部用户信息
    async getuserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 分页页面存储多少条数据
    handleSizeChange(newSize) {
      window.sessionStorage.setItem('newSize', newSize)
      this.queryInfo.pagesize = Number(window.sessionStorage.getItem('newSize'))
      this.getuserList()
    },
    // 当前数据页面处于那一页
    handleCurrentChange(newPagenum) {
      // 将页面数据存储在浏览器
      window.sessionStorage.setItem('newPagenum', newPagenum)
      this.queryInfo.pagenum = Number(
        window.sessionStorage.getItem('newPagenum')
      )
      this.getuserList()
    },
    // 监听switch开关状态的改变
    async userStateChange(value) {
      const { data: res } = await this.$http.put(
        `users/${value.id}/state/${value.mg_state}`
      )
      if (res.meta.status !== 200) {
        value.mg_state = !value.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('更新用户状态成功！')
    },
    // 点击添加用户事件
    addUserInfo() {
      this.$refs.addUserInfoRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.userFormAdd)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败！')
        }
        // 成功的返回提示
        this.$message.success('添加用户成功！')
        // 隐藏对话框
        this.dialogFormVisible = false
        // 重新刷新用户列表
        this.getuserList()
      })
    },
    // 获取当前点击的用户信息存入data中，渲染页面
    async showAmendUser(id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取去用户信息失败，请稍后再试！')
      }
      this.userEditPut = res.data
      this.dialogShowAmendUser = true
    },
    // 更修改用户信息并提交
    userEditPutInfo() {
      // TODO：当用户的信息与旧的的信息相同时，不发起请求
      this.$refs.userEditPutRef.validate(async (valid) => {
        if (!valid) return
        // 发起修改用户信息的网络请求  //发起put提交请求
        const { data: res } = await this.$http.put(
          `users/${this.userEditPut.id}`,
          { email: this.userEditPut.email, mobile: this.userEditPut.mobile }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败，请稍后再试')
        }
        this.$message.success('更新用户信息成功！')
        // 重新获取用户最新的信息
        this.getuserList()
        // 点击确定后关闭对话框
        this.dialogShowAmendUser = false
      })
    },
    // 删除用户信息
    deleteUserInfo(id) {
      this.$confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${id}`)
          if (res.meta.status !== 200) {
            return this.$message.error('删除失败！请稍后再试')
          }
          // 更新删除后的信息
          this.getuserList()
          this.$message.success(' 删除成功!')
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 展示分配角色的对话框
    async allotUserRights(userInfo) {
      this.allotUserInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败！')
      }
      this.roleRightsList = res.data
      this.dialogAllotRights = true
    },
    // 点击确定发起修改请求
    async putUserSelect() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色！')
      }
      const { data: res } = await this.$http.put(
        `users/${this.allotUserInfo.id}/role`,
        {
          rid: this.selectedRoleId
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改角色权限失败！')
      }
      this.$message.success('修改角色权限成功！')
      this.getuserList()
      this.dialogAllotRights = false
    },
    // 关闭对话框后将残留数据清空
    closeClear() {
      this.allotUserInfo = {}
      this.roleRightsList = []
      this.selectedRoleId = ''
    }
  }
}
</script>

<style lang="less" scoped>
.el-form-item {
  width: 100%;
}
</style>
